﻿using System.Windows.Controls;
using AgFractal.Fractals;
using FluxJpeg.Core;
using System.Runtime.Serialization;
using System.Xml;

namespace AgFractal
{
    internal static class SaveUtils
    {

        internal static void Save(SavedData sd)
        {
            var dialog = new SaveFileDialog { Filter = "agfractal files(agf.*)|*.agf" };

            if (dialog.ShowDialog() != true)
                return;

            var ser = new DataContractSerializer(typeof(SavedData));
            using (var fileStream = dialog.OpenFile())
            {
                using (var writer = XmlWriter.Create(fileStream, new XmlWriterSettings { 
                    ConformanceLevel = ConformanceLevel.Fragment }))
                {
                    ser.WriteObject(writer, sd);
                    writer.Flush();
                    writer.Close();
                }
            }
        }

        internal static void SaveToJPEG()
        {
            SaveFileDialog saveDlg = new SaveFileDialog { Filter = "JPEG Files (*.jpeg)|*.jpeg" };
            if (saveDlg.ShowDialog() == true)
            {
                using (var fs = saveDlg.OpenFile())
                {
                    SaveToJpeg(fs);
                }
            }
        }

        static void SaveToJpeg(System.IO.Stream fs)
        {
            var png = FractalManager.Instance.img;
            int width = FractalManager.Instance.imageWidth;
            int height = FractalManager.Instance.imageHeight;
            int bands = 3;
            byte[][,] raster = new byte[bands][,];

            //Code From http://stackoverflow.com/questions/1139200/using-fjcore-to-encode-silverlight-writeablebitmap
            for (int i = 0; i < bands; i++)
            {
                raster[i] = new byte[width, height];
            }

            for (int row = 0; row < height; row++)
            {
                for (int column = 0; column < width; column++)
                {
                    byte red, green, blue, alpha;

                    png.GetPixel(column, row, out red, out green, out blue, out alpha);

                    raster[0][column, row] = red;
                    raster[1][column, row] = green;
                    raster[2][column, row] = blue;
                }
            }

            FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(
                new ColorModel { colorspace = ColorSpace.RGB },
                raster);
            FluxJpeg.Core.Encoder.JpegEncoder encoder = new FluxJpeg.Core.Encoder.JpegEncoder(img, 80, fs);
            encoder.Encode();
        }
    }
}